/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.gruposp2p.aularest.model.controller;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import org.gruposp2p.aularest.model.Competence;
import org.gruposp2p.aularest.model.Itemcalificable;
import java.util.ArrayList;
import java.util.Collection;
import org.gruposp2p.aularest.model.controller.exceptions.NonexistentEntityException;
import org.gruposp2p.aularest.model.controller.exceptions.PreexistingEntityException;

/**
 *
 * @author jj
 */
public class CompetenceJpaController {

    public CompetenceJpaController() {
        emf = Persistence.createEntityManagerFactory("AulaRest_PU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Competence competence) throws PreexistingEntityException, Exception {
        if (competence.getItemcalificableCollection() == null) {
            competence.setItemcalificableCollection(new ArrayList<Itemcalificable>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Itemcalificable> attachedItemcalificableCollection = new ArrayList<Itemcalificable>();
            for (Itemcalificable itemcalificableCollectionItemcalificableToAttach : competence.getItemcalificableCollection()) {
                itemcalificableCollectionItemcalificableToAttach = em.getReference(itemcalificableCollectionItemcalificableToAttach.getClass(), itemcalificableCollectionItemcalificableToAttach.getId());
                attachedItemcalificableCollection.add(itemcalificableCollectionItemcalificableToAttach);
            }
            competence.setItemcalificableCollection(attachedItemcalificableCollection);
            em.persist(competence);
            for (Itemcalificable itemcalificableCollectionItemcalificable : competence.getItemcalificableCollection()) {
                itemcalificableCollectionItemcalificable.getCompetenceCollection().add(competence);
                itemcalificableCollectionItemcalificable = em.merge(itemcalificableCollectionItemcalificable);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCompetence(competence.getId()) != null) {
                throw new PreexistingEntityException("Competence " + competence + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Competence competence) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Competence persistentCompetence = em.find(Competence.class, competence.getId());
            Collection<Itemcalificable> itemcalificableCollectionOld = persistentCompetence.getItemcalificableCollection();
            Collection<Itemcalificable> itemcalificableCollectionNew = competence.getItemcalificableCollection();
            Collection<Itemcalificable> attachedItemcalificableCollectionNew = new ArrayList<Itemcalificable>();
            for (Itemcalificable itemcalificableCollectionNewItemcalificableToAttach : itemcalificableCollectionNew) {
                itemcalificableCollectionNewItemcalificableToAttach = em.getReference(itemcalificableCollectionNewItemcalificableToAttach.getClass(), itemcalificableCollectionNewItemcalificableToAttach.getId());
                attachedItemcalificableCollectionNew.add(itemcalificableCollectionNewItemcalificableToAttach);
            }
            itemcalificableCollectionNew = attachedItemcalificableCollectionNew;
            competence.setItemcalificableCollection(itemcalificableCollectionNew);
            competence = em.merge(competence);
            for (Itemcalificable itemcalificableCollectionOldItemcalificable : itemcalificableCollectionOld) {
                if (!itemcalificableCollectionNew.contains(itemcalificableCollectionOldItemcalificable)) {
                    itemcalificableCollectionOldItemcalificable.getCompetenceCollection().remove(competence);
                    itemcalificableCollectionOldItemcalificable = em.merge(itemcalificableCollectionOldItemcalificable);
                }
            }
            for (Itemcalificable itemcalificableCollectionNewItemcalificable : itemcalificableCollectionNew) {
                if (!itemcalificableCollectionOld.contains(itemcalificableCollectionNewItemcalificable)) {
                    itemcalificableCollectionNewItemcalificable.getCompetenceCollection().add(competence);
                    itemcalificableCollectionNewItemcalificable = em.merge(itemcalificableCollectionNewItemcalificable);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = competence.getId();
                if (findCompetence(id) == null) {
                    throw new NonexistentEntityException("The competence with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Competence competence;
            try {
                competence = em.getReference(Competence.class, id);
                competence.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The competence with id " + id + " no longer exists.", enfe);
            }
            Collection<Itemcalificable> itemcalificableCollection = competence.getItemcalificableCollection();
            for (Itemcalificable itemcalificableCollectionItemcalificable : itemcalificableCollection) {
                itemcalificableCollectionItemcalificable.getCompetenceCollection().remove(competence);
                itemcalificableCollectionItemcalificable = em.merge(itemcalificableCollectionItemcalificable);
            }
            em.remove(competence);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Competence> findCompetenceEntities() {
        return findCompetenceEntities(true, -1, -1);
    }

    public List<Competence> findCompetenceEntities(int maxResults, int firstResult) {
        return findCompetenceEntities(false, maxResults, firstResult);
    }

    private List<Competence> findCompetenceEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Competence as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Competence findCompetence(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Competence.class, id);
        } finally {
            em.close();
        }
    }

    public int getCompetenceCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Competence as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
